package com.example.demo.service;

import com.example.demo.model.Author;
import com.example.demo.model.BlogPost;
import com.example.demo.repository.AuthorRepository;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class AuthorService {
    @Autowired
    private AuthorRepository authorRepository;

    @Autowired
    private BlogPostService blogPostService;

    @Transactional
    public Author saveAuthor(Author author) {
        Author savedAuthor = authorRepository.save(author);
        for (BlogPost blogPost : author.getBlogPosts()) {
            blogPost.setAuthor(savedAuthor);
            blogPostService.saveBlogPost(blogPost);
        }
        return savedAuthor;
    }

    public Optional<Author> getAuthorByName(String name) {
        return authorRepository.findByName( name);
    }
//
//    public Optional<Author> getBlogPostsByAuthorName(String name) {
//        return authorRepository.findByName(name).map(author -> {
//            author.setBlogPosts(blogPostService.getBlogPostsByAuthor(author));
//            return author;
//        });
//    }
}
